/**
 * 创建request请求
 * @returns
 */
const request = (
    url, //: string, //接口地址
    type, //: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT', //请求方式
    data, //: AnyObject, //请求的参数
    header, //: any //设置请求的 header
    custom //自定义配置
) => {
    // 全局添加请求头
    let obj = {
		ChannelId: uni.getStorageSync("appId") ? uni.getStorageSync("appId") : ''
    };
    if (header) {
        let headers = Object.assign(header, obj);

        header = headers;
    } else {
        header = obj;
    }
    if (type === 'GET' && data) {
        url = url + '?' + tansParams(data);
        url = url.slice(0, -1);
        data = {};
    }

    return new Promise((resolve, reject) => {
        uni.showLoading({
            title: '加载中',
            mask: true,
        });
        uni.request({
            url: url,
            method: type,
            data,
            header,
            success(res) {
                uni.hideLoading();
                const data = res.data;
                if (res.statusCode === 200) {
                    resolve(data);
                } else {
                    uni.showToast({
                        title: '服务出错！',
                        icon: 'none',
                    });
                    reject(data);
                }
            },
            fail(err) {
                uni.hideLoading();

                uni.showToast({
                    title: '服务出错',
                    icon: 'none',
                });
                reject(err);
            },
        });
    });
};

export function get(url, data = {}, options = {}) {
    const header = options.header;
    const custom = options.custom;
    const type = 'GET';
    return request(url, type, data, header, custom);
}
export function post(url, data = {}, options = {}) {
    const header = options.header;
    const custom = options.custom;
    const type = 'POST';
    return request(url, type, data, header, custom);
}

/**
 * 参数处理 允许对象深层
 * @param {*} params  参数
 */
function tansParams(params) {
    let result = '';
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        var part = encodeURIComponent(propName) + '=';
        if (value !== null && value !== '' && typeof value !== 'undefined') {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && value[key] !== '' && typeof value[key] !== 'undefined') {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + '=';
                        result += subPart + encodeURIComponent(value[key]) + '&';
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + '&';
            }
        }
    }
    return result;
}
